package com.example.demo.utils.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.demo.config.Result;
import com.example.demo.utils.PageParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.ParameterizedType;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 基础接口，为了获取注入 Service 和 实体类型
 *
 * </p>
 * @param <ServiceImpl> Service
 * @param <Entity> 实体
 * @param <DTO> DTO
 * @param <SaveDTO> SaveDTO
 * @param <UpdateDTO> UpdateDTO
 * @author dapangdong
 * @since 2022-06-09 19:01:22
 */
public class BaseController<ServiceImpl extends IService<Entity>,Entity, DTO, SaveDTO,UpdateDTO> {

    @Autowired
    protected ServiceImpl baseService;

    private Class<Entity> entityClass = null;

    /**
     * 获取实体的类型
     * @return 实体的类型
     */
    public Class<Entity> getEntityClass() {
        if (entityClass == null) {
            this.entityClass = (Class<Entity>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1];
        }
        return this.entityClass;
    }

    /**
     * 新增或修改
     * @param model 保存参数
     * @return 新增或修改结果
     */
    @PostMapping("/saveOrupdate")
    @ApiOperation(value = "新增或修改",notes = "id不存在即新增，反则修改" )
    public Result<Boolean> saveOrUpdate(@RequestBody Entity model) {
        return Result.success(baseService.saveOrUpdate(model));
    }

    /**
     * 新增
     * @param saveDTO 保存参数
     * @return 新增结果
     */
    @PostMapping("/save")
    @ApiOperation(value = "新增",notes = "新增" )
    public Result<Entity> save(@RequestBody SaveDTO saveDTO) {
        Entity model = BeanUtil.toBean(saveDTO, getEntityClass());
        BeanUtil.copyProperties(saveDTO,model);
        return Result.success(model);
    }

    /**
     * 删除
     * @param ids 参数ids
     * @return 删除结果
     */
    @DeleteMapping("/deleteById")
    @ApiOperation(value = "删除",notes = "删除" )
    public Result<?> delete(@RequestBody List<Long> ids) {
        baseService.removeByIds(ids);
        return Result.success(ids,"成功");
    }

    /**
     * 修改
     * @param updateDTO 修改参数
     * @return 修改结果
     */
    @PutMapping("/update")
    @ApiOperation(value = "修改",notes = "修改" )
    public Result<?> update(@RequestBody UpdateDTO updateDTO) {
        Entity model = BeanUtil.toBean(updateDTO, getEntityClass());
        BeanUtil.copyProperties(updateDTO,model);
        return Result.success(baseService.updateById(model));
    }

    /**
     * 单体查询
     * @param id 参数id
     * @return 查询结果
     */
    @GetMapping("/getById")
    @ApiOperation(value = "单体查询",notes = "单体查询" )
    public Result<?> getById(@ApiParam(value = "id",required = true) String id) {
        Entity model = baseService.getById(id);
        if (model!=null){
            return Result.success(model);
        }
        else {
            return Result.success(String.format("无%s的数据",id));
        }
    }

    /**
     * 列表查询（非分页）
     * @param model 查询参数
     * @return 查询结果
     */
    @PostMapping("/list")
    @ApiOperation(value = "列表查询",notes = "列表查询" )
    public Result<Object> list(@RequestBody Entity model) {
        LambdaQueryWrapper<Entity> wrapper=new LambdaQueryWrapper<>(model);
        List<Entity> list =  baseService.list(wrapper);

        Map<String,Object> map=new HashMap<>(2);
        map.put("records",list);
        map.put("total",list.size());
        return Result.success(map);
    }

    /**
     * 分页查询
     * @param page 查询参数
     * @return 查询结果
     */
    @PostMapping("/query")
    @ApiOperation(value = "分页查询",notes = "分页查询" )
    public Result<IPage<Entity>> query(@RequestBody PageParams<Entity> page) throws Exception {
        QueryWrapper<Entity> queryWrapper=new QueryWrapper<>(page.getModel());
        // 设置分页、排序
        return Result.success(baseService.page(page.buildPage(getEntityClass()),queryWrapper));
    }





}
